<template>
  <div class="container">
    <el-page-header :icon="ArrowLeft" @back="goBack" title="返回" class="page-header">
      <template #content>
        <div class="page-header-content">
          <h1>育秧数据解析可视化</h1>
          <p>传感器数据解析结果可视化展示</p>
        </div>
      </template>
    </el-page-header>

    <el-divider />

    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="data-input" shadow="hover">
          <template #header>
            <div class="card-header">
              <h2><el-icon><DataLine /></el-icon> 数据输入</h2>
            </div>
          </template>
          <el-form :model="formData" label-position="top">
            <el-form-item label="原始数据">
              <el-input
                v-model="dataContent"
                type="textarea"
                :rows="6"
                placeholder="请输入原始数据..."
                resize="none"
              />
            </el-form-item>
            <el-form-item label="湿度阈值">
              <el-input-number
                v-model="moistureThreshold"
                :precision="1"
                :step="0.1"
                :min="0"
                style="width: 200px"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="processInputData" :icon="Search">解析数据</el-button>
              <el-button @click="resetForm" :icon="Refresh">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card class="summary-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h2><el-icon><InfoFilled /></el-icon> 数据摘要</h2>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="有效数据点(低于3000)">
              <el-statistic :value="cnValue">
                <template #suffix>
                  <span>点</span>
                </template>
              </el-statistic>
            </el-descriptions-item>
            <el-descriptions-item label="湿度阈值超标次数">
              <el-statistic :value="nValue" value-style="color: #f56c6c">
                <template #suffix>
                  <span>次</span>
                </template>
              </el-statistic>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <h2><el-icon><TrendCharts /></el-icon> 霍尔传感器数据变化趋势</h2>
            </div>
          </template>
          <div class="chart-container" ref="hallChart"></div>
        </el-card>
      </el-col>
      <el-col :xs="24" :lg="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <h2><el-icon><TrendCharts /></el-icon> 湿度数据变化趋势</h2>
            </div>
          </template>
          <div class="chart-container" ref="humidityChart"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="mt-20">
      <el-col :span="24">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h2><el-icon><Document /></el-icon> 解析数据</h2>
              <el-input
                v-model="searchQuery"
                placeholder="搜索数据..."
                style="width: 200px"
                clearable
                :prefix-icon="Search"
              />
            </div>
          </template>
          <el-table
            :data="filteredData"
            style="width: 100%"
            border
            stripe
            highlight-current-row
            :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
            v-loading="tableLoading"
          >
            <el-table-column prop="index" label="序号" width="80" sortable />
            <el-table-column prop="actualData" label="霍尔数据" width="120" sortable />
            <el-table-column prop="humData" label="湿度数据" width="120">
              <template #default="scope">
                {{ scope.row.humData.toString(16).toUpperCase() }}
              </template>
            </el-table-column>
            <el-table-column prop="humidityValue" label="湿度值" width="120" sortable>
              <template #default="scope">
                <span :class="{ 'text-danger': scope.row.exceedsThreshold }">
                  {{ scope.row.humidityValue.toFixed(2) }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="scope.row.exceedsThreshold ? 'danger' : 'success'" effect="light">
                  {{ scope.row.exceedsThreshold ? '超标' : '正常' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :total="filteredData.length"
              layout="total, sizes, prev, pager, next, jumper"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              background
            />
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { 
  ElTable, ElTableColumn, ElPagination, ElTag, ElCard, ElForm, ElFormItem, 
  ElInput, ElButton, ElRow, ElCol, ElDivider, ElPageHeader, ElIcon, 
  ElDescriptions, ElDescriptionsItem, ElStatistic, ElInputNumber
} from 'element-plus'
import { 
  Search, Refresh, ArrowLeft, DataLine, InfoFilled, TrendCharts, Document 
} from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'

export default {
  name: 'SeedlingDataAnalysis',
  components: {
    ElTable, ElTableColumn, ElPagination, ElTag, ElCard, ElForm, ElFormItem,
    ElInput, ElButton, ElRow, ElCol, ElDivider, ElPageHeader, ElIcon,
    ElDescriptions, ElDescriptionsItem, ElStatistic, ElInputNumber
  },
  data() {
    return {
      dataContent: '1249022700020002125e02350002000212480232000200031257023400020003125a023300020002125702350002000112550225000200021251022600020001125b022600020002125d022600020001124802250002000212420223000000021248022300010002125f022700020002124c0223000200011248022d000200021247022e00020002124f0230000200051249022f000100021242022d0002000212400223000200011236022300010006124902250002000412480224000200021249022500020004125c022500020001125e0225000100021262022700020001124c022200020001125b0230000100001246022d000100021246022d000200031242022d00010002125d023000020001124402270001000412440229000200011249022900020001124d022800020000124d022a000200001248022800010001124c022a00020002124b022900020001124402280001000112460231000200031248023300020003124b0233000100021257023400020002124502330002000212440227000200051248022500020003124902250002000312490224000200021244022400010002124b022400020002125e022600020004124c022300020004124a022400020002124a022d000200021271023100020002',
      moistureThreshold: 0,
      cnValue: 0,
      nValue: 0,
      parsedData: [],
      hallChart: null,
      humidityChart: null,
      currentPage: 1,
      pageSize: 10,
      formData: {},
      searchQuery: '',
      tableLoading: false,
      Search,
      Refresh,
      ArrowLeft,
      DataLine,
      InfoFilled,
      TrendCharts,
      Document
    }
  },
  computed: {
    filteredData() {
      if (!this.searchQuery) {
        return this.parsedData.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
          .map((item, index) => ({
            ...item,
            index: (this.currentPage - 1) * this.pageSize + index + 1
          }))
      }
      
      const query = this.searchQuery.toLowerCase()
      return this.parsedData.filter(item => 
        item.actualData.toString().includes(query) || 
        item.humData.toString(16).toUpperCase().includes(query.toUpperCase()) ||
        item.humidityValue.toString().includes(query)
      ).slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        .map((item, index) => ({
          ...item,
          index: (this.currentPage - 1) * this.pageSize + index + 1
        }))
    }
  },
  methods: {
    parseData(content, moistureThreshold) {
      const resultMap = {
        parsedData: [],
        cn: 0,
        n: 0
      }

      let lastActualData = -1

      for (let i = 0; i < content.length; i += 16) {
        if (i + 16 > content.length) break

        const datum = content.substring(i, i + 16)
        const actualData = parseInt(datum.substring(0, 4), 16)
        const humData = parseInt(datum.substring(4, 8), 16)
        const humidityValue = humData / 50.0

        if ((lastActualData < 0 || lastActualData > 3000) && actualData < 3000) {
          resultMap.cn++
        }
        lastActualData = actualData

        if (humidityValue > moistureThreshold) {
          resultMap.n++
        }

        resultMap.parsedData.push({
          actualData,
          humData,
          humidityValue,
          exceedsThreshold: humidityValue > moistureThreshold
        })
      }

      return resultMap
    },
    updateCharts(parsedData, moistureThreshold) {
      const indices = parsedData.map((_, index) => index + 1)
      const hallData = parsedData.map(data => data.actualData)
      const humidityValues = parsedData.map(data => data.humidityValue)

      // 更新霍尔数据图表
      if (!this.hallChart) {
        this.hallChart = echarts.init(this.$refs.hallChart)
      }
      
      const hallOption = {
        title: {
          text: '霍尔传感器数据变化趋势',
          left: 'center',
          show: false
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: indices,
          name: '序号',
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          name: '霍尔数据'
        },
        series: [{
          name: '霍尔传感器数据',
          type: 'line',
          data: hallData,
          smooth: true,
          lineStyle: {
            color: '#4BC0C0',
            width: 2
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(75, 192, 192, 0.3)'
              }, {
                offset: 1,
                color: 'rgba(75, 192, 192, 0.1)'
              }]
            }
          },
          emphasis: {
            focus: 'series'
          }
        }]
      }
      this.hallChart.setOption(hallOption)

      // 更新湿度数据图表
      if (!this.humidityChart) {
        this.humidityChart = echarts.init(this.$refs.humidityChart)
      }

      const humidityOption = {
        title: {
          text: '湿度数据变化趋势',
          left: 'center',
          show: false
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['湿度值', '阈值'],
          top: 10
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: indices,
          name: '序号',
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          name: '湿度值'
        },
        series: [{
          name: '湿度值',
          type: 'line',
          data: humidityValues,
          smooth: true,
          lineStyle: {
            color: '#36A2EB',
            width: 2
          },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0,
              y: 0,
              x2: 0,
              y2: 1,
              colorStops: [{
                offset: 0,
                color: 'rgba(54, 162, 235, 0.3)'
              }, {
                offset: 1,
                color: 'rgba(54, 162, 235, 0.1)'
              }]
            }
          },
          emphasis: {
            focus: 'series'
          }
        }, {
          name: '阈值',
          type: 'line',
          data: Array(indices.length).fill(moistureThreshold),
          lineStyle: {
            type: 'dashed',
            color: '#FF6384',
            width: 2
          },
          emphasis: {
            focus: 'series'
          }
        }]
      }
      this.humidityChart.setOption(humidityOption)
    },
    processInputData() {
      if (!this.dataContent) {
        ElMessage({
          message: '请输入原始数据',
          type: 'warning'
        })
        return
      }

      this.tableLoading = true
      
      // 模拟处理延迟
      setTimeout(() => {
        const result = this.parseData(this.dataContent, this.moistureThreshold)
        this.cnValue = result.cn
        this.nValue = result.n
        this.parsedData = result.parsedData
        this.updateCharts(result.parsedData, this.moistureThreshold)
        this.tableLoading = false
        
        ElMessage({
          message: '数据解析成功',
          type: 'success'
        })
      }, 500)
    },
    resetForm() {
      this.moistureThreshold = 0
      this.searchQuery = ''
      ElMessage({
        message: '表单已重置',
        type: 'info'
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    goBack() {
      ElMessage({
        message: '返回上一页',
        type: 'info'
      })
      // 实际应用中可以使用 this.$router.go(-1) 返回上一页
    }
  },
  mounted() {
    this.processInputData()
    window.addEventListener('resize', () => {
      this.hallChart?.resize()
      this.humidityChart?.resize()
    })
  },
  beforeUnmount() {
    window.removeEventListener('resize', () => {
      this.hallChart?.resize()
      this.humidityChart?.resize()
    })
    this.hallChart?.dispose()
    this.humidityChart?.dispose()
  }
}
</script>

<style scoped>
.container {
  max-width: 1800px;
  margin: 20px auto;
  padding: 20px;
  background-color: #ffffff;
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light);
}

.page-header {
  margin-bottom: 20px;
}

.page-header-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.page-header-content h1 {
  font-size: 2em;
  margin: 0;
  color: var(--el-text-color-primary);
}

.page-header-content p {
  font-size: 1em;
  color: var(--el-text-color-secondary);
  margin: 5px 0 0 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  color: var(--el-text-color-primary);
  font-size: 1.2em;
  display: flex;
  align-items: center;
  gap: 8px;
}

.chart-container {
  height: 400px;
  width: 100%;
}

.chart-card {
  height: 100%;
  margin-bottom: 20px;
}

.mt-20 {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
}

.text-danger {
  color: var(--el-color-danger);
  font-weight: bold;
}

:deep(.el-form-item__label) {
  font-weight: bold;
  color: var(--el-text-color-primary);
}

:deep(.el-textarea__inner) {
  font-family: monospace;
  line-height: 1.5;
}

:deep(.el-tag) {
  border-radius: 4px;
}

:deep(.el-descriptions__label) {
  font-weight: bold;
}

:deep(.el-statistic__number) {
  font-size: 1.5em;
  font-weight: bold;
}

@media (max-width: 768px) {
  .container {
    padding: 10px;
    margin: 10px;
  }
  
  .chart-container {
    min-width: auto;
    height: 300px;
  }
}
</style> 